// cloudfunctions/updateOrderStatus/index.js
const cloud = require('wx-server-sdk');
const TcbRouter = require('tcb-router');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

exports.main = async (event, context) => {
  const app = new TcbRouter({ event });

  // 设置跨域 CORS
  app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', 'http://localhost:5173');
    ctx.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type');
    if (event.httpMethod === 'OPTIONS') {
        ctx.status = 204;
        return;
    }
    await next();
  });

  // 更新状态逻辑
  app.router('POST', '/', async (ctx) => {
    const { orderId, status } = event;
    try {
      await db.collection('orders').doc(orderId).update({
        data: { printStatus: status },
      });
      ctx.body = { success: true };
    } catch (e) {
      ctx.body = { success: false, error: e };
    }
  });
  
  app.use(async (ctx) => {
      if (ctx.method !== 'POST') {
          ctx.body = { success: false, message: '请求方法不正确' };
      }
  });

  return app.serve();
};